// Inject script for QKL Wallet Extension
// 这个脚本会被注入到网页中，提供钱包功能

interface QKLWalletProvider {
  isQKLWallet: boolean;
  version: string;
  request: (method: string, params?: any[]) => Promise<any>;
  requestAccounts: () => Promise<string[]>;
  getAccounts: () => Promise<string[]>;
  sendTransaction: (tx: any) => Promise<string>;
  signMessage: (message: string) => Promise<string>;
  signTypedData: (typedData: any) => Promise<string>;
  switchChain: (chainId: string) => Promise<void>;
  addChain: (chainParams: any) => Promise<void>;
}

declare global {
  interface Window {
    qklWallet: QKLWalletProvider;
    ethereum: QKLWalletProvider;
  }
}

// 创建QKL钱包提供者
const createQKLWalletProvider = (): QKLWalletProvider => {
  return {
    isQKLWallet: true,
    version: '1.0.0',
    
    request: async (method: string, params: any[] = []): Promise<any> => {
      return new Promise((resolve, reject) => {
        const requestId = Date.now() + Math.random();
        
        // 发送请求到扩展
        window.postMessage({
          type: 'QKL_WALLET_REQUEST',
          id: requestId,
          method: method,
          params: params
        }, '*');
        
        // 监听响应
        const handleResponse = (event: MessageEvent) => {
          if (event.data.type === 'QKL_WALLET_RESPONSE' && 
              event.data.id === requestId) {
            window.removeEventListener('message', handleResponse);
            
            if (event.data.error) {
              reject(new Error(event.data.error));
            } else {
              resolve(event.data.result);
            }
          }
        };
        
        window.addEventListener('message', handleResponse);
        
        // 超时处理
        setTimeout(() => {
          window.removeEventListener('message', handleResponse);
          reject(new Error('请求超时'));
        }, 30000);
      });
    },
    
    // 便捷方法
    requestAccounts: function() {
      return this.request('eth_requestAccounts');
    },
    
    getAccounts: function() {
      return this.request('eth_accounts');
    },
    
    sendTransaction: function(tx: any) {
      return this.request('eth_sendTransaction', [tx]);
    },
    
    signMessage: function(message: string) {
      return this.request('personal_sign', [message]);
    },
    
    signTypedData: function(typedData: any) {
      return this.request('eth_signTypedData', [typedData]);
    },
    
    switchChain: function(chainId: string) {
      return this.request('wallet_switchEthereumChain', [{ chainId }]);
    },
    
    addChain: function(chainParams: any) {
      return this.request('wallet_addEthereumChain', [chainParams]);
    }
  };
};

// 注入钱包提供者
if (!window.qklWallet) {
  window.qklWallet = createQKLWalletProvider();
  
  // 兼容MetaMask API
  if (window.ethereum) {
    window.ethereum.isQKLWallet = true;
    window.ethereum.qklWallet = window.qklWallet;
  } else {
    window.ethereum = window.qklWallet;
  }
  
  // 触发连接事件
  window.dispatchEvent(new Event('ethereum#initialized'));
  
  console.log('QKL钱包已注入到页面');
}
